﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using WebSocketChat.Common.Web;

namespace WebSocketChat.Web.Controllers
{
    public class ChatController : Controller
    {
        private Models.WebSocketChatEntities db = new Models.WebSocketChatEntities();
        // GET: Chat
        public ActionResult Index()
        {
            ViewBag.Title = "小鹿聊天";
            if (Session["UserLogin"] == null)
                return RedirectToAction("SignIn");

            return View(GetName());
        }

        public ActionResult SignIn()
        {
            ViewBag.Title = "小鹿登录";
            return View(GetName());
        }

        public ActionResult SignUp()
        {
            ViewBag.Title = "小鹿注册";
            return View(GetName());
        }

        public ActionResult SignOut()
        {
            Session["UserLogin"] = null;
            return RedirectToAction("SignIn");
        }

        public ActionResult ValidImage()
        {
            string code = string.Empty;
            byte[] bytes = ValidateCode.CreateValidateGraphic(out code, 4, 100, 40, 20);
            Session["validcode"] = code.ToLower();
            return File(bytes, @"image/jpeg");
        }

        [HttpPost]
        public JsonResult Login(FormUser user)
        {
            ResultObject<string> res = new ResultObject<string>();
            //if (user.ValidCode.ToLower() == Session["validcode"].ToString().ToLower())
            //{
                var dbUser = db.ChatUser.FirstOrDefault(t => (t.LoginID == user.LoginID || t.Telephone == user.LoginID) && t.PassWords == user.PassWords);
                if (dbUser != null)
                {
                    Session["UserLogin"] = dbUser;
                    res.code = 0;
                    res.msg = "success";
                }
                else
                {
                    res.code = 404;
                    res.msg = "用户名或密码不正确";
                }
            //}
            //else
            //{
            //    res.code = 404;
            //    res.msg = "验证码错误";
            //}
            return Json(res);
        }

        [HttpPost]
        public JsonResult Register(FormUser user)
        {
            ResultObject<string> res = new ResultObject<string>();
            if (user.ValidCode.ToLower() == Session["validcode"].ToString().ToLower())
            {
                var muser = db.ChatUser.Add(new Models.ChatUser()
                {
                    Birthday = user.Birthday,
                    Age = (DateTime.Now - user.Birthday).Days / 365,
                    LoginID = user.LoginID,
                    PassWords = user.PassWords,
                    UserStateID = 6,
                    NickName = user.LoginID,
                    Sex = user.Sex == 1 ? true : false,
                    HeadPortrait = "head.jpg"
                });
                db.SaveChanges();
                var friendGroup = db.FriendGroups.Add(new Models.FriendGroups()
                {
                    Name = "我的好友",
                    UserID = muser.ID
                });
                db.SaveChanges();
                var friend = db.Friends.Add(new Models.Friends()
                {
                    FirendID = muser.ID,
                    Name = muser.NickName,
                    UserID = muser.ID,
                    FriendGroupsID = friendGroup.ID,
                    FriendTypeID = 1
                });

                if (db.SaveChanges() > 0)
                {
                    res.code = 0;
                    res.msg = "success";
                }
                else
                {
                    res.code = 404;
                    res.msg = "注册失败";
                }
            }
            else
            {
                res.code = 404;
                res.msg = "验证码错误";
            }
            return Json(res);
        }

        [HttpPost]
        public JsonResult UploadImg()
        {
            ResultObject<UploadFileInfo> res = new ResultObject<UploadFileInfo>();
            try
            {
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase f = Request.Files["file"];
                    string folderPath = DateTime.Now.ToString("yyyyMMdd") + "/";
                    string uploadPath = Server.MapPath("~/Images/UploadImg/");
                    if (!Directory.Exists(uploadPath + folderPath))
                        Directory.CreateDirectory(uploadPath + folderPath);
                    string filepath = folderPath + Guid.NewGuid() + Path.GetExtension(f.FileName);
                    f.SaveAs(uploadPath + filepath);

                    res.code = 0;
                    res.msg = "success";
                    res.data = new Controllers.UploadFileInfo()
                    {
                        name = Path.GetFileNameWithoutExtension(f.FileName),
                        src = "../Images/UploadImg/" + filepath
                    };
                }
                else
                {
                    res.code = 404;
                    res.msg = "文件未找到";

                }
            }
            catch (Exception ex)
            {
                res.code = 404;
                res.msg = ex.Message;
            }
            return Json(res);
        }

        [HttpGet]
        public JsonResult ChatInit(int userID)
        {
            ResultObject res = new Controllers.ResultObject();
            try
            {
                var user = db.ChatUser.Select(t => new InitUser() { id = t.ID, avatar = "../Images/" + t.HeadPortrait, sign = t.SignaTures, status = t.UserStateID == 6 ? "offline" : "online", username = t.NickName }).FirstOrDefault(t => t.id == userID);
                List<InitFriend> groups = new List<InitFriend>();

                var fgs = db.FriendGroups.Where(t => t.UserID == userID).ToList();
                foreach (var item in fgs)
                {
                    InitFriend group = new InitFriend();
                    group.id = item.ID;
                    group.groupname = item.Name;
                    group.list = new List<InitUser>();

                    var friends = db.Friends.Where(t => t.UserID == userID && t.FriendGroupsID == item.ID && t.FirendID != userID).ToList();
                    foreach (var friend in friends)
                    {
                        group.list.Add(new InitUser()
                        {
                            id = friend.FirendID,
                            username = friend.Name,
                            sign = friend.ChatUser.SignaTures,
                            avatar = "../Images/" + friend.ChatUser.HeadPortrait,
                            status = friend.ChatUser.UserStateID == 6 ? "offline" : "online"
                        });
                    }
                    groups.Add(group);
                }

                List<InitGroup> userGroups = new List<InitGroup>();
                var userGroup = db.GroupView.Where(t => t.UserID == userID).Select(t => new InitGroup()
                {
                    id = t.ID.Value,
                    avatar = "../Images/" + t.ICon,
                    groupname = t.Name
                }).ToList();

                res.code = 0;
                res.data = new { mine = user, friend = groups, group = userGroup };
                res.msg = "success";
            }
            catch (Exception ex)
            {
                res.code = 404;
                res.msg = ex.Message;
            }

            return Json(res, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult GroupMember(int id)
        {
            ResultObject res = new Controllers.ResultObject();
            try
            {
                var list = db.GroupMember.Where(t => t.GroupID == id).Select(t => new InitUser()
                {
                    id = t.ID.Value,
                    avatar = "../Images/" + t.HeadPortrait,
                    sign = t.SignaTures,
                    username = t.GroupNick
                }).ToList();

                res.code = 0;
                res.data = new { list = list };
                res.msg = "success";
            }
            catch (Exception ex)
            {
                res.code = 404;
                res.msg = ex.Message;
            }
            return Json(res, JsonRequestBehavior.AllowGet);
        }

        private string[] GetName()
        {
            string[] infos = new string[4];
            var user = Session["UserLogin"] as Models.ChatUser;
            if (user != null)
            {
                infos[0] = user.LoginID;
                infos[1] = user.NickName;
                infos[2] = user.HeadPortrait;
                infos[3] = user.ID.ToString();
            }
            else
            {
                infos[0] = "";
                infos[1] = "";
                infos[2] = "";
                infos[3] = "";
            }
            return infos;
        }
    }

    public class InitUser
    {
        public string username { get; set; }
        public int id { get; set; }
        public string status { get; set; }
        public string sign { get; set; }
        public string avatar { get; set; }
    }

    public class InitFriend
    {
        public string groupname { get; set; }
        public int id { get; set; }
        public List<InitUser> list { get; set; }
    }

    public class InitGroup
    {
        public string groupname { get; set; }
        public int id { get; set; }
        public string avatar { get; set; }
    }

    public class FormUser
    {
        public string LoginID { get; set; }
        public string PassWords { get; set; }
        public int Sex { get; set; }
        public DateTime Birthday { get; set; }
        public string ValidCode { get; set; }
    }
}